import java.util.Arrays;

public class CocktailSortOptimized {

    public static void sort(int array[]) {
        if (array == null || array.length <= 1) {
            return;
        }

        int left = 0;
        int right = array.length - 1;
        int lastLeftSwapped = 0;
        int lastRightSwapped = 0;

        while (left < right) {
            boolean isSorted = true;
            lastRightSwapped = left;

            // 奇数轮：从左向右比较和交换
            for (int j = left; j < right; j++) {
                if (array[j] > array[j + 1]) {
                    int tmp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = tmp;
                    isSorted = false;
                    lastRightSwapped = j;
                }
            }
            right = lastRightSwapped;
            if (isSorted) {
                break;
            }

            isSorted = true;
            lastLeftSwapped = right;

            // 偶数轮：从右向左比较和交换
            for (int j = right; j > left; j--) {
                if (array[j] < array[j - 1]) {
                    int tmp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = tmp;
                    isSorted = false;
                    lastLeftSwapped = j;
                }
            }
            left = lastLeftSwapped;
            if (isSorted) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = new int[]{2, 3, 4, 5, 6, 7, 8, 1};
        sort(array);
        System.out.println(Arrays.toString(array));
    }
}
